package com.muyu.danmo.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.mapper.DanmoPrintingDoorMapper;
import com.muyu.danmo.mapper.DanmoPrintingFavoriteMapper;
import com.muyu.danmo.mapper.DanmoPrintingLikesMapper;
import com.muyu.danmo.mapper.DanmoPrintingMessageMapper;
import com.muyu.danmo.service.IDanmoPrintingMessageService;
import com.muyu.danmo.service.IDanmoPrintingTypeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 印刷出版Service业务层处理
 *
 * @author yangle
 * @date 2024-10-15
 */
@Log4j2
@Service
public class DanmoPrintingMessageServiceImpl implements IDanmoPrintingMessageService {
    @Autowired
    private DanmoPrintingMessageMapper danmoPrintingMessageMapper;

    @Autowired
    private DanmoPrintingLikesMapper danmoPrintingLikesMapper;

    @Autowired
    private DanmoPrintingFavoriteMapper danmoPrintingFavoriteMapper;

    /**
     * 查询印刷出版
     *
     * @param id 印刷出版主键
     * @return 印刷出版
     */
    @Override
    public DanmoPrintingMessage selectDanmoPrintingMessageById(Long id) {
        DanmoPrintingMessage danmoPrintingMessage = danmoPrintingMessageMapper.selectDanmoPrintingMessageById(id);
        List<DanmoPrintingType> list = danmoPrintingMessageMapper.selectDanmoPrintingTypeList(id);
        danmoPrintingMessage.setDanmoPrintingTypeList(list);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (danmoPrintingLikesMapper.existsByUserIdAndPrintingClassId(loginUser.getUserid(), id)) {
            danmoPrintingMessage.setIsLike("已点赞");
        }
        if (danmoPrintingFavoriteMapper.existsByUserIdAndPrintingClassId(loginUser.getUserid(), id)) {
            danmoPrintingMessage.setIsCollection("已收藏");
        }

        if (!danmoPrintingMessage.getUserId().equals(loginUser.getUserid())){
            danmoPrintingMessage.setBusinessLicense(null);
            danmoPrintingMessage.setFrontOfIdCard(null);
            danmoPrintingMessage.setReverseSideOfIdCard(null);
        }



//        if (danmoPrintingMessage == null) {
//            System.out.println("未找到指定的打印消息，ID: " + id);
//            return null; // 或根据需要抛出异常
//        }
//
//        List<MergedType> mergedTypes = new ArrayList<>();
//        List<DanmoPrintingPicture> pictures = Optional.ofNullable(danmoPrintingMessage.getDanmoPrintingPictureList()).orElse(Collections.emptyList());
//        List<DanmoPrintingTypeRelation> relations = Optional.ofNullable(danmoPrintingMessage.getDanmoPrintingTypeRelationList()).orElse(Collections.emptyList());
//
//        // 处理每个图片
//        for (DanmoPrintingPicture picture : pictures) {
//            // 处理 relationType，使用 pictureType 查找对应的 relation
//            String relationType = "未定义关系"; // 默认关系名称
//            for (DanmoPrintingTypeRelation relation : relations) {
//                if (relation.getPrintingTypeId().equals(picture.getPictureType())) {
//                    relationType = relation.getTypeName(); // 根据 pictureType 查找 relationType
//                    break; // 找到匹配后跳出循环
//                }
//            }
//            // 处理类型名称
//            List<?> printingTypes = Optional.ofNullable(picture.getDanmoPrintingTypeList()).orElse(Collections.emptyList());
//            String typeName = "未定义类型"; // 默认类型名称
//            // 遍历并检查类型
//            if (!printingTypes.isEmpty()) {
//                Object firstType = printingTypes.get(0);
//                if (firstType instanceof DanmoPrintingType) {
//                    typeName = ((DanmoPrintingType) firstType).getTypeName();
//                } else if (firstType instanceof DanmoPrintingPictureType) {
//                    typeName = ((DanmoPrintingPictureType) firstType).getTypeName();
//                }
//            }
//            mergedTypes.add(new MergedType(
//                    picture.getPictureUrl(),
//                    picture.getDescription(),
//                    typeName,
//                    relationType
//            ));
//        }
//
//// 设置合并后的列表
//        danmoPrintingMessage.setDoorEndList(mergedTypes);
        danmoPrintingMessage.setViews(danmoPrintingMessage.getViews() + 1);
        danmoPrintingMessageMapper.updateDanmoPrintingMessage(danmoPrintingMessage);
        return danmoPrintingMessage;

    }

    /**
     * 查询印刷出版列表
     *
     * @param danmoPrintingMessage 印刷出版
     * @return 印刷出版
     */
    @Override
    public List<DanmoPrintingMessage> selectDanmoPrintingMessageList(DanmoPrintingMessage danmoPrintingMessage) {
        return danmoPrintingMessageMapper.selectDanmoPrintingMessageList(danmoPrintingMessage);
    }




    @Autowired
    private IDanmoPrintingTypeService danmoPrintingTypeService;
    /**
     * 新增印刷出版
     *
     * @param danmoPrintingMessage 印刷出版
     * @return 结果
     */
    @Transactional
    @Override
    public Result insertDanmoPrintingMessage(DanmoPrintingMessage danmoPrintingMessage) {
        try {

            Result result = verifyWhether(danmoPrintingMessage);
            if (result!=null)
            {
                return result;
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userid = loginUser.getUserid();
            DanmoPrintingMessage danmoPrintingMessage1 = new DanmoPrintingMessage();
            danmoPrintingMessage1.setUserId(userid);
            danmoPrintingMessage.setUserId(userid);
            /*List<DanmoPrintingMessage> danmoPrintingMessages = danmoPrintingMessageMapper.selectDanmoPrintingMessageList(danmoPrintingMessage1);
            if (danmoPrintingMessages.size()>0) {
                return Result.error("您已发布过印刷出版信息，请勿重复发布");
            }*/
            // 第一步：插入 DanmoPrintingMessage 并获取返回的 ID
            danmoPrintingMessageMapper.insertDanmoPrintingMessage(danmoPrintingMessage);
            // 获取插入后返回的 ID
            Long messageId = danmoPrintingMessage.getId();

/*            List<DanmoPrintingType> danmoPrintingTypeList = danmoPrintingMessage.getDanmoPrintingTypeList();
            if (danmoPrintingTypeList != null && !danmoPrintingTypeList.isEmpty()) {
                for (DanmoPrintingType danmoPrintingType : danmoPrintingTypeList) {
                    danmoPrintingType.setMessageId(messageId);
                    danmoPrintingTypeService.insertDanmoPrintingType(danmoPrintingType);
                }
            }*/

            // 第二步：为 DanmoPrintingDoor 和 DanmoPrintingWorks 和  InteriorPhotos 设置 messageId
            setMessageIdForDoors(danmoPrintingMessage.getDanmoPrintingDoorList(), messageId);
            setMessageIdForWorks(danmoPrintingMessage.getDanmoPrintingWorksList(), messageId);
            setMessageIdPrintingType(danmoPrintingMessage.getDanmoPrintingTypeList(), messageId);
            setMessageIdInteriorPhotos(danmoPrintingMessage.getDanmoPrintingInteriorPhotosList(), messageId);

            // 第三步：插入其他相关数据
            insertDanmoPrintingDoor(danmoPrintingMessage.getDanmoPrintingDoorList());
            insertDanmoPrintingInteriorPhotos(danmoPrintingMessage.getDanmoPrintingInteriorPhotosList());
            insertDanmoPrintingWorks(danmoPrintingMessage.getDanmoPrintingWorksList());
            insertDanmoPrintingTypes(danmoPrintingMessage.getDanmoPrintingTypeList());


            return Result.success(danmoPrintingMessage,"添加成功");
        } catch (Exception e) {
            // 日志记录异常信息
            log.error("Error inserting DanmoPrintingMessage: ", e);
            // 事务回滚
            return Result.error("添加失败");
        }
    }

    /**
     * 批量插入印刷出版类型对象
     * @param danmoPrintingTypeList
     */
    private void insertDanmoPrintingTypes(List<DanmoPrintingType> danmoPrintingTypeList) {
        if (CollectionUtils.isNotEmpty(danmoPrintingTypeList)) {
            danmoPrintingMessageMapper.insertDanmoPrintingTypes(danmoPrintingTypeList);
        }
    }

    /**
     * 设置 messageId
     * @param danmoPrintingTypeList
     * @param messageId
     */
    private void setMessageIdPrintingType(List<DanmoPrintingType> danmoPrintingTypeList, Long messageId) {
        if (CollectionUtils.isNotEmpty(danmoPrintingTypeList)) {
            for (DanmoPrintingType danmoPrintingType : danmoPrintingTypeList) {
                danmoPrintingType.setMessageId(messageId); // 设置 messageId
            }
        }
    }

    private Result verifyWhether(DanmoPrintingMessage danmoPrintingMessage) {
        if (danmoPrintingMessage.getTitle() == null || danmoPrintingMessage.getTitle().equals("")) {
            return Result.error("请填写标题");
        }
        if (danmoPrintingMessage.getIntroduction() == null || danmoPrintingMessage.getIntroduction().equals("")) {
            return Result.error("请填写店铺介绍");
        }

        if (danmoPrintingMessage.getContactInfo() == null || danmoPrintingMessage.getContactInfo().equals("")) {
            return Result.error("请填写联系方式");
        }
        if (danmoPrintingMessage.getAddress() == null || danmoPrintingMessage.getAddress().equals("")) {
            return Result.error("请填写店铺地址");
        }

        if (danmoPrintingMessage.getCitycode()==null || danmoPrintingMessage.getCitycode().equals("")){
            return Result.error("请选择省份");
        }
        if (danmoPrintingMessage.getCitycode()==null  || danmoPrintingMessage.getCitycode().equals("")){
            return Result.error("请选择市");
        }
        if (danmoPrintingMessage.getCountycode()==null  || danmoPrintingMessage.getCountycode().equals("")){
            return Result.error("请选择县");
        }
        return null;
    }

    private void setMessageIdInteriorPhotos(List<DanmoPrintingInteriorPhotos> danmoPrintingInteriorPhotosList, Long messageId) {
        if (CollectionUtils.isNotEmpty(danmoPrintingInteriorPhotosList)) {
            for (DanmoPrintingInteriorPhotos interiorPhoto : danmoPrintingInteriorPhotosList) {
                interiorPhoto.setMessageId(messageId); // 设置 messageId
            }
        }
    }


    // 设置 DanmoPrintingDoor 的 messageId
    private void setMessageIdForDoors(List<DanmoPrintingDoor> danmoPrintingDoorList, Long messageId) {
        if (CollectionUtils.isNotEmpty(danmoPrintingDoorList)) {
            for (DanmoPrintingDoor door : danmoPrintingDoorList) {
                door.setMessageId(messageId); // 设置 messageId
            }
        }
    }

    // 设置 DanmoPrintingWorks 的 messageId
    private void setMessageIdForWorks(List<DanmoPrintingWorks> danmoPrintingWorksList, Long messageId) {
        if (CollectionUtils.isNotEmpty(danmoPrintingWorksList)) {
            for (DanmoPrintingWorks work : danmoPrintingWorksList) {
                work.setMessageId(messageId); // 设置 messageId
            }
        }
    }

    private void insertDanmoPrintingWorks(List<DanmoPrintingWorks> danmoPrintingWorksList) {
        if (CollectionUtils.isNotEmpty(danmoPrintingWorksList)) {
            danmoPrintingMessageMapper.batchDanmoPrintingWorks(danmoPrintingWorksList);
        }
    }

    private void insertDanmoPrintingInteriorPhotos(List<DanmoPrintingInteriorPhotos> danmoPrintingInteriorPhotosList) {
        if (CollectionUtils.isNotEmpty(danmoPrintingInteriorPhotosList)) {
            danmoPrintingMessageMapper.batchDanmoPrintingInteriorPhotos(danmoPrintingInteriorPhotosList);
        }
    }

    private void insertDanmoPrintingDoor(List<DanmoPrintingDoor> danmoPrintingDoorList) {
        if (CollectionUtils.isNotEmpty(danmoPrintingDoorList)) {
            danmoPrintingMessageMapper.batchDanmoPrintingDoor(danmoPrintingDoorList);
        }
    }


    /**
     * 修改印刷出版
     *
     * @param danmoPrintingMessage 印刷出版
     * @return 结果
     */
    @Transactional
    @Override
    public Result updateDanmoPrintingMessage(DanmoPrintingMessage danmoPrintingMessage) {
        try{
            Result result = verifyWhether(danmoPrintingMessage);
            if (result!=null)
            {
                return result;
            }
            danmoPrintingMessage.setUpdateTime(DateUtils.getNowDate());
            danmoPrintingMessageMapper.updateDanmoPrintingMessage(danmoPrintingMessage);
//        updateDanmoPrintingPicture(danmoPrintingMessage);
//            updateDanmoPrintingType(danmoPrintingMessage);
            Long messageId = danmoPrintingMessage.getId();
            deleteOldRelatedData(messageId);

            // 第二步：为 DanmoPrintingDoor 和 DanmoPrintingWorks 和  InteriorPhotos 设置 messageId
            setMessageIdForDoors(danmoPrintingMessage.getDanmoPrintingDoorList(), messageId);
            setMessageIdForWorks(danmoPrintingMessage.getDanmoPrintingWorksList(), messageId);
            setMessageIdInteriorPhotos(danmoPrintingMessage.getDanmoPrintingInteriorPhotosList(), messageId);
            setMessageIdPrintingType(danmoPrintingMessage.getDanmoPrintingTypeList(), messageId);


            // 第三步：插入其他相关数据
            insertDanmoPrintingDoor(danmoPrintingMessage.getDanmoPrintingDoorList());
            insertDanmoPrintingInteriorPhotos(danmoPrintingMessage.getDanmoPrintingInteriorPhotosList());
            insertDanmoPrintingWorks(danmoPrintingMessage.getDanmoPrintingWorksList());
            insertDanmoPrintingTypes(danmoPrintingMessage.getDanmoPrintingTypeList());

            return Result.success(danmoPrintingMessage,"更新成功");
        }catch (Exception e){
            return Result.error("更新失败");
        }


    }

    private void deleteOldRelatedData(Long messageId) {
        List<Long> danmoDoorIdList = danmoPrintingMessageMapper.selectDanmoDoorList(messageId);
        if (CollectionUtils.isNotEmpty(danmoDoorIdList)) {
            danmoPrintingMessageMapper.deleteDanmoPrintingDoorByPrintingIds(danmoDoorIdList);
        }

        List<Long> danmoWorksIdList = danmoPrintingMessageMapper.selectDanmoWorksList(messageId);
        if (CollectionUtils.isNotEmpty(danmoWorksIdList)) {
            danmoPrintingMessageMapper.deleteDanmoPrintingWorksByPrintingIds(danmoWorksIdList);
        }

        List<Long> danmoInteriorPhotos = danmoPrintingMessageMapper.seletDanmoInteriorPhotos(messageId);
        if (CollectionUtils.isNotEmpty(danmoInteriorPhotos)) {
            danmoPrintingMessageMapper.deleteDanmoInteriorPhotos(danmoInteriorPhotos);
        }

        List<Long> danmoPrintingInteriorPhotos = danmoPrintingMessageMapper.seletDanmoPrintingInteriorPhotos(messageId);
        if (CollectionUtils.isNotEmpty(danmoPrintingInteriorPhotos)) {
            danmoPrintingMessageMapper.deletePrintingInteriorPhotos(danmoPrintingInteriorPhotos);
        }


    }

//    /**
//     * 更新印刷出版图片信息
//     *
//     * @param danmoPrintingMessage 印刷出版对象
//     */
//    public void updateDanmoPrintingPicture(DanmoPrintingMessage danmoPrintingMessage) {
//        Long id = danmoPrintingMessage.getId();
//        // 首先删除旧的图片信息
//        danmoPrintingMessageMapper.deleteDanmoPrintingPictureByIds(new Long[]{id});
//        // 然后添加新的图片信息
//        List<DanmoPrintingPicture> danmoPrintingPictureList = danmoPrintingMessage.getDanmoPrintingPictureList();
//        if (CollectionUtils.isNotEmpty(danmoPrintingPictureList)) {
//            for (DanmoPrintingPicture danmoPrintingPicture : danmoPrintingPictureList) {
//                danmoPrintingPicture.setPrintingId(id);
//            }
//            danmoPrintingMessageMapper.batchDanmoPrintingPicture(danmoPrintingPictureList);
//        }
//    }

    public void updateDanmoPrintingType(DanmoPrintingMessage danmoPrintingMessage) {
        Long id = danmoPrintingMessage.getId();
        // 首先删除旧的类型信息
        danmoPrintingMessageMapper.deleteDanmoPrintingTypeByIds(id);
        // 然后添加新的类型信息
        List<DanmoPrintingTypeRelation> danmoPrintingTypeRelationList = danmoPrintingMessage.getDanmoPrintingTypeRelationList();
        if (CollectionUtils.isNotEmpty(danmoPrintingTypeRelationList)) {
            for (DanmoPrintingTypeRelation danmoPrintingTypeRelation : danmoPrintingTypeRelationList) {
                danmoPrintingTypeRelation.setPrintingMessageId(id);
            }
            danmoPrintingMessageMapper.batchDanmoPrintingType(danmoPrintingTypeRelationList);
        }
    }

    /**
     * 批量删除印刷出版
     *
     * @param ids 需要删除的印刷出版主键
     * @return 结果
     */
    @Transactional
    @Override
    public Result deleteDanmoPrintingMessageByIds(Long[] ids) {
//        danmoPrintingMessageMapper.deleteDanmoPrintingPictureByPrintingIds(ids);
      try {
          for (Long id : ids) {
              danmoPrintingMessageMapper.deleteDanmoPrintingTypeBys(id);
              deleteOldRelated(id);
          }
          danmoPrintingMessageMapper.deleteDanmoPrintingMessageByIds(ids);
          return Result.success(ids,"删除成功");
      }catch (Exception e){
          return Result.error("删除成功");
      }

    }

    private void deleteOldRelated(Long id) {
        danmoPrintingMessageMapper.deleteDanmoPrintingDoorList(id);
        danmoPrintingMessageMapper.deleteDanmoPrintingInteriorPhotosList(id);
        danmoPrintingMessageMapper.deleteDanmoPrintingWorksList(id);
        danmoPrintingMessageMapper.deletePrintingInteriorPhotoList(id);
    }

    /**
     * 删除印刷出版信息
     *
     * @param id 印刷出版主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDanmoPrintingMessageById(Long id) {
        danmoPrintingMessageMapper.deleteDanmoPrintingPictureByPrintingId(id);
        return danmoPrintingMessageMapper.deleteDanmoPrintingMessageById(id);
    }

    @Override
    public Result danmoPrintingMessageByUserId(Long userId) {
        DanmoPrintingMessage danmoPrintingMessage = danmoPrintingMessageMapper.danmoPrintingMessageByUserId(userId);
        if (danmoPrintingMessage==null){
            return Result.error("暂无数据");
        }
        return Result.success(danmoPrintingMessageMapper.selectDanmoPrintingMessageById(danmoPrintingMessage.getId()));
    }

    /**
     * 新增印刷出版图片信息
     *
     * @param danmoPrintingMessage 印刷出版对象
     */
    public void insertDanmoPrintingPicture(DanmoPrintingMessage danmoPrintingMessage) {
        List<DanmoPrintingPicture> danmoPrintingPictureList = danmoPrintingMessage.getDanmoPrintingPictureList();
        Long id = danmoPrintingMessage.getId();
        if (StringUtils.isNotNull(danmoPrintingPictureList)) {
            List<DanmoPrintingPicture> list = new ArrayList<DanmoPrintingPicture>();
            for (DanmoPrintingPicture danmoPrintingPicture : danmoPrintingPictureList) {
                danmoPrintingPicture.setPrintingId(id);
                list.add(danmoPrintingPicture);
            }
            if (list.size() > 0) {
                danmoPrintingMessageMapper.batchDanmoPrintingPicture(list);
            }
        }
    }

    /**
     * 新增印刷出版类型
     *
     * @param danmoPrintingMessage 印刷出版对象
     */
    public void insertDanmoPrintingType(DanmoPrintingMessage danmoPrintingMessage) {
        List<DanmoPrintingTypeRelation> danmoPrintingTypeRelationList = danmoPrintingMessage.getDanmoPrintingTypeRelationList();
        Long id = danmoPrintingMessage.getId();
        if (StringUtils.isNotNull(danmoPrintingTypeRelationList)) {
            List<DanmoPrintingTypeRelation> list = new ArrayList<DanmoPrintingTypeRelation>();
            for (DanmoPrintingTypeRelation danmoPrintingTypeRelation : danmoPrintingTypeRelationList) {
                danmoPrintingTypeRelation.setPrintingMessageId(id);
                list.add(danmoPrintingTypeRelation);
            }
            if (list.size() > 0) {
                danmoPrintingMessageMapper.batchDanmoPrintingType(list);
            }
        }
    }
}
